import { useState, useEffect } from 'react';
import { DraggableItem } from '../CanvasContainer';
import styles from './index.less';

interface ElementPropertiesPanelProps {
  element: DraggableItem | null;
  onUpdateProperties: (properties: Partial<DraggableItem>) => void;
}

const ElementPropertiesPanel: React.FC<ElementPropertiesPanelProps> = ({
  element,
  onUpdateProperties,
}) => {
  const [width, setWidth] = useState<number>(0);
  const [height, setHeight] = useState<number>(0);
  const [rotation, setRotation] = useState<number>(0);
  const [opacity, setOpacity] = useState<number>(1);
  const [lockRatio, setLockRatio] = useState<boolean>(false);
  const [aspectRatio, setAspectRatio] = useState<number>(1);

  // 当选中元素变化时，更新表单值
  useEffect(() => {
    if (element) {
      setWidth(element.width);
      setHeight(element.height);
      setRotation(element.rotation || 0);
      setOpacity(element.opacity || 1);
      setLockRatio(element.lockRatio || false);
      setAspectRatio(element.width / element.height);
    }
  }, [element]);

  // 处理宽度变化
  const handleWidthChange = (value: number) => {
    const newWidth = Math.max(10, value); // 最小宽度限制
    setWidth(newWidth);

    if (element && lockRatio) {
      // 保持比例调整高度
      const newHeight = Math.round(newWidth / aspectRatio);
      setHeight(newHeight);
      onUpdateProperties({
        id: element.id,
        width: newWidth,
        height: newHeight,
      });
    } else if (element) {
      onUpdateProperties({ id: element.id, width: newWidth });
    }
  };

  // 处理高度变化
  const handleHeightChange = (value: number) => {
    const newHeight = Math.max(10, value); // 最小高度限制
    setHeight(newHeight);

    if (element && lockRatio) {
      // 保持比例调整宽度
      const newWidth = Math.round(newHeight * aspectRatio);
      setWidth(newWidth);
      onUpdateProperties({
        id: element.id,
        width: newWidth,
        height: newHeight,
      });
    } else if (element) {
      onUpdateProperties({ id: element.id, height: newHeight });
    }
  };

  // 处理旋转变化
  const handleRotationChange = (value: number) => {
    setRotation(value);
    if (element) {
      onUpdateProperties({ id: element.id, rotation: value });
    }
  };

  // 处理透明度变化
  const handleOpacityChange = (value: number) => {
    setOpacity(value);
    if (element) {
      onUpdateProperties({ id: element.id, opacity: value });
    }
  };

  // 处理锁定比例切换
  const handleLockRatioChange = (checked: boolean) => {
    setLockRatio(checked);
    if (element) {
      onUpdateProperties({ id: element.id, lockRatio: checked });
    }
  };

  if (!element) {
    return (
      <div className={styles.container}>
        <div className={styles.emptyState}>未选中任何元素</div>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <h3>元素属性</h3>
        <div className={styles.elementName}>{element.name || '未命名元素'}</div>
      </div>

      <div className={styles.propertiesSection}>
        <h4>尺寸</h4>
        <div className={styles.sizeControl}>
          <div className={styles.inputGroup}>
            <label htmlFor="widthInput">宽度</label>
            <div className={styles.inputWithUnit}>
              <input
                id="widthInput"
                type="number"
                value={width}
                onChange={(e) =>
                  handleWidthChange(parseInt(e.target.value) || 0)
                }
                min="10"
                step="1"
              />
              <span>px</span>
            </div>
          </div>

          <div className={styles.inputGroup}>
            <label htmlFor="heightInput">高度</label>
            <div className={styles.inputWithUnit}>
              <input
                id="heightInput"
                type="number"
                value={height}
                onChange={(e) =>
                  handleHeightChange(parseInt(e.target.value) || 0)
                }
                min="10"
                step="1"
              />
              <span>px</span>
            </div>
          </div>

          <div className={styles.lockRatioControl}>
            <input
              id="lockRatioCheckbox"
              type="checkbox"
              checked={lockRatio}
              onChange={(e) => handleLockRatioChange(e.target.checked)}
            />
            <label htmlFor="lockRatioCheckbox">锁定宽高比</label>
          </div>
        </div>
      </div>

      <div className={styles.propertiesSection}>
        <h4>样式</h4>
        <div className={styles.styleControl}>
          <div className={styles.inputGroup}>
            <label htmlFor="rotationInput">旋转</label>
            <div className={styles.inputWithUnit}>
              <input
                id="rotationInput"
                type="number"
                value={rotation}
                onChange={(e) =>
                  handleRotationChange(parseInt(e.target.value) || 0)
                }
                min="0"
                max="359"
                step="1"
              />
              <span>°</span>
            </div>
          </div>

          <div className={styles.inputGroup}>
            <label htmlFor="opacityInput">透明度</label>
            <div className={styles.inputWithUnit}>
              <input
                id="opacityInput"
                type="range"
                min="0"
                max="1"
                step="0.05"
                value={opacity}
                onChange={(e) =>
                  handleOpacityChange(parseFloat(e.target.value) || 0)
                }
              />
              <span>{Math.round(opacity * 100)}%</span>
            </div>
          </div>
        </div>
      </div>

      {element.type === 'rect' && (
        <div className={styles.propertiesSection}>
          <h4>矩形属性</h4>
          <div className={styles.shapeControl}>
            <div className={styles.inputGroup}>
              <label htmlFor="colorInput">颜色</label>
              <input
                id="colorInput"
                type="color"
                value={element.color || '#1890ff'}
                onChange={(e) => {
                  if (element) {
                    onUpdateProperties({
                      id: element.id,
                      color: e.target.value,
                    });
                  }
                }}
              />
            </div>
          </div>
        </div>
      )}

      {element.type === 'text' && (
        <div className={styles.propertiesSection}>
          <h4>文本属性</h4>
          <div className={styles.textControl}>
            <div className={styles.inputGroup}>
              <label htmlFor="textInput">文本内容</label>
              <input
                id="textInput"
                type="text"
                value={element.text || ''}
                onChange={(e) => {
                  if (element) {
                    onUpdateProperties({
                      id: element.id,
                      text: e.target.value,
                    });
                  }
                }}
                placeholder="输入文本内容"
              />
            </div>

            <div className={styles.inputGroup}>
              <label htmlFor="textColorInput">文本颜色</label>
              <input
                id="textColorInput"
                type="color"
                value={element.color || '#faad14'}
                onChange={(e) => {
                  if (element) {
                    onUpdateProperties({
                      id: element.id,
                      color: e.target.value,
                    });
                  }
                }}
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ElementPropertiesPanel;
